package org.example.paymentservice.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.paymentservice.config.PaymentProperties;
import org.example.paymentservice.entity.Order;
import org.example.paymentservice.service.OrderProcessor;
import org.example.paymentservice.service.PaymentService;
import org.example.paymentservice.service.WebhookHandler;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service("wechat_pay_webhook")
@RequiredArgsConstructor
public class WeChatPayWebhookHandler implements WebhookHandler {
    private final PaymentProperties paymentProperties;
    private final PaymentService paymentService;
    private final OrderProcessor orderProcessor;
    private final WXPay wxPay;

    @Override
    public void handlePaymentNotification(String payload, Map<String, String> headers) {
        try {
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(payload);
            
            if (verifySignature(payload, notifyMap.get("sign"))) {
                String returnCode = notifyMap.get("return_code");
                String resultCode = notifyMap.get("result_code");
                String transactionId = notifyMap.get("out_trade_no");
                
                if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                    // 支付成功，更新订单状态
                    paymentService.validatePayment(transactionId);
                    log.info("WeChatPay payment notification processed successfully for transaction: {}", transactionId);
                } else {
                    log.error("WeChatPay payment failed for transaction: {}, reason: {}", 
                            transactionId, notifyMap.get("err_code_des"));
                }
            } else {
                log.error("Invalid signature for WeChatPay notification");
            }
        } catch (Exception e) {
            log.error("Error processing WeChatPay notification", e);
            throw new RuntimeException("Failed to process payment notification", e);
        }
    }

    @Override
    public void handleRefundNotification(String payload, Map<String, String> headers) {
        try {
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(payload);
            
            if (verifySignature(payload, notifyMap.get("sign"))) {
                String returnCode = notifyMap.get("return_code");
                String refundStatus = notifyMap.get("refund_status");
                String transactionId = notifyMap.get("out_trade_no");
                
                if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(refundStatus)) {
                    // 退款成功，更新订单状态
                    orderProcessor.updateOrderStatus(
                        Long.valueOf(notifyMap.get("out_trade_no")), 
                        Order.PaymentStatus.REFUNDED
                    );
                    log.info("WeChatPay refund notification processed successfully for transaction: {}", transactionId);
                } else {
                    log.error("WeChatPay refund failed for transaction: {}, reason: {}", 
                            transactionId, notifyMap.get("refund_status_desc"));
                }
            } else {
                log.error("Invalid signature for WeChatPay refund notification");
            }
        } catch (Exception e) {
            log.error("Error processing WeChatPay refund notification", e);
            throw new RuntimeException("Failed to process refund notification", e);
        }
    }

    @Override
    public boolean verifySignature(String payload, String signature) {
        try {
            return WXPayUtil.isSignatureValid(payload, paymentProperties.getWechatPay().getApiKey());
        } catch (Exception e) {
            log.error("Error verifying WeChatPay signature", e);
            return false;
        }
    }
}